package com.zxn.service;

import com.zxn.utils.ElasticUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightUtils;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;

import java.util.ArrayList;
import java.util.List;

/**
 * program: springbootelastic
 * description: ${description}
 * author: zxn
 * create: 2019-04-07 21:01
 **/
public class IkPinyinAnalyzer {

    public static List<String> suggestForIkPinyin(String prefix) {

        TransportClient client = ElasticUtils.getClient();
        QueryBuilder py = QueryBuilders.matchQuery("name.pinyin",prefix);
        QueryBuilder qb = QueryBuilders.boolQuery().must(py);
        SearchResponse response = client.prepareSearch("medcl").setTypes("folks")
                                        .setQuery(qb)
                                        .get();
        SearchHits hits = response.getHits();
        List<String> suggestList = new ArrayList<String>();
        for (SearchHit hit: hits) {
            suggestList.add(hit.getSourceAsString());
            System.out.println(hit.getSource());
        }
        System.out.println(hits.totalHits);
        return suggestList;
    }

    public static List<Text> suggestForIkPinyinHighlight(String prefix) {

        TransportClient client = ElasticUtils.getClient();
        QueryBuilder py = QueryBuilders.matchQuery("name.pinyin",prefix);
        QueryBuilder qb = QueryBuilders.boolQuery().must(py);
        HighlightBuilder hiBuilder=new HighlightBuilder();
        hiBuilder.preTags("<h2>");
        hiBuilder.postTags("</h2>");
        hiBuilder.field("name.pinyin");
        SearchResponse response = client.prepareSearch("highlight").setTypes("folks")
                .setQuery(qb)
                .highlighter(hiBuilder)
                .get();
        SearchHits hits = response.getHits();
        List<Text> suggestList = new ArrayList<Text>();
        for (SearchHit hit: hits) {
            suggestList.add(hit.getHighlightFields().get("name.pinyin").getFragments()[0]);
           // System.out.println(hit.getHighlightFields().get("name.pinyin"));
        }
        System.out.println(hits.totalHits);
        return suggestList;
    }

    public static void main(String[] args) {
        List<Text> result = suggestForIkPinyinHighlight("nan");
        for (Text str : result) {
            System.out.println(str);
        }
    }
}
